<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Home\Controller;
use User\Api\UserApi;

/**
 * 用户控制器
 * 包括用户中心，用户登录及注册
 */
class UserController extends HomeController {

    /* 用户中心首页 */
    public function index(){
        !is_login() && $this->referer('User/login', U('User/index'));
        $Member = M('Member');
    
        $info = $Member->where(array(
            'uid' => UID
        ))
        ->field('uid',
                'nickname',
                'sex',
                'qq',
                'money',
                'avatar',
                'birthday',
                'score',
                'last_login_ip',
                'last_login_time',
                'freeze_amount',
                'amount') ->find();
        if ($info  ) {
            $info['avatar_path'] = get_cover($info['avatar'],'path');
        }
        $ext_info=M('ucenter_member')->where(  array( 'id' => UID )) ->field( array( 'username', 'email','mobile')) ->find();
        if ($info  && $ext_info) {
            $info=array_merge($info,$ext_info);
        } 
        $this->assign('info',$info);
        
        $prefix = C('DB_PREFIX');
        $l_table = $prefix.('order');
        $m_table = $prefix.('order_product');
        $r_table = $prefix.('order_shipping');
        $model=D('order');
        $model = $model->table($l_table.' l')
        ->join($m_table.' m ON m.order_id=l.id')
        ->join($r_table . ' r on r.order_id=l.id');
        
        $options['field'] = array('l.id,l.id order_id,l.status,m.product_id,r.code,r.shipping_code');
        $join_map=array();
        $json_map['uid']=UID;
        $join_map['l.status']=array('between',array('2','4'));        
        $OPT = new \ReflectionProperty($model,'options');
        $OPT->setAccessible(true);        
        $options['group'] = 'l.id';
        $options['where']=$join_map;        
        $options = array_merge( (array)$OPT->getValue($model), $options );
        $model->setProperty('options',$options);        
        $Product_list = $model->select();
        foreach($Product_list as &$item){            
            $item['image_path']=get_cover(get_table_field($item['product_id'],'product_id','cover_id','product_image'),'path');
            $tem_ship = getExpress($item['shipping_code'], $item['code']);
            if($tem_ship){
                $item['shipping']=$tem_ship['data'][count($tem_ship)-1];
            }
        }
        $this->assign('product_list',$Product_list);
        $this->display();
    }
    
    /* 个人信息 */
    public function info(){
        !is_login() && $this->referer('User/login', U('User/info'));
        if(IS_POST){
            $avatar=I('request.avatar');
            $sex=I('request.sex');
            $nickname=I('request.nickname');
            $data=array();
            $data['sex']=$sex;
            $data['avatar']=$avatar;
            $data['nickname']=$nickname;
            $M_member=M('member');
            $M_member->where(array('uid'=>UID))->save($data) !==false ?
            $this->ajaxReturn(array('status'=>11)) : $this->error('修改失败');
        }else{
            $M_member=M('member');
    
            $member_info=$M_member->where(array('uid'=>UID))->find();
            $member_info['avatar_path']=get_cover($member_info['avatar'],'path');
            $this->assign('info',$member_info);
            $this->display();
        }
    }
   
    /* 收货地址管理 */
    public function receives(){
        !is_login() && $this->referer('User/login', U('User/receives'));
        if(IS_POST){
             
        }else{
            $M_member_receive=M('member_receive');
            $id=I('request.id');
    
            $info=$M_member_receive->find($id);
            $this->assign('info',$info);
            $mreceive_list=$M_member_receive->where(array('uid'=>UID))->select();
            foreach($mreceive_list as &$item){
                $item['address_full']=
                get_table_field($item['province_id'],'province_id','province','hat_province')
                .get_table_field($item['city_id'],'city_id','city','hat_city')
                .get_table_field($item['area_id'],'area_id','area','hat_area').$item['address'];
            }
            $this->assign('receive_list',$mreceive_list);
            $this->display();
        }
    }

    
    /* 编辑收货地址 */
    public function Editreceive(){
        !is_login() && $this->referer(U('User/login'), U('User/receives'));
        $Member_receive = M('Member_receive');
        $method=I('request.method');
        $id=I('request.id');
        if($method=='del'){
            $Member_receive->where(array('id'=>$id))->delete() ? $this->success('成功') : $this->error('删除失败');
            exit;
        }
         
        $mobile = I('request.mobile');
        $realname = I('request.realname');
        $province_id = I('request.province_id', 0);
        $city_id = I('request.city_id', 0);
        $area_id = I('request.area_id', 0);
        $address = I('request.address');
        $is_default = I('request.is_default',0);
        !preg_match('/^[\x{4e00}-\x{9fa5}]{1,10}+$/u', $realname) && $this->error( '请输入收货人姓名，必须为中文');
        !preg_match('/1[3458]{1}\d{9}$/', $mobile) && $this->error('请正确输入您的手机号码');        
        !get_table_field($province_id, 'province_id', 'province_id', 'Hat_province') && $this->error('选择的省份没有匹配对象');
        !get_table_field($city_id, 'city_id', 'city_id', 'Hat_city') && $this->error('选择的城市没有匹配对象');
        !get_table_field($area_id, 'area_id', 'area_id', 'Hat_area') && $this->error('选择的区县没有匹配对象');
        !preg_match('/^[\x{4e00}-\x{9fa5}][\x{4e00}-\x{9fa5}A-Za-z0-9_-]{1,50}+$/u', $address) && $this->error('详细地址长度必须在2~50个字符');
        !preg_match('/^0|1$/', $is_default) && $this->error('是否为默认地址只能为0或1');
        $data = array(
                'uid' => UID,
                'realname' => $realname,
                'mobile' => $mobile,
                'province_id' => $province_id,
                'city_id' => $city_id,
                'area_id' => $area_id,
                'address' => $address,
                'is_default' => $is_default,
                'create_time' => NOW_TIME,
                'update_time' => NOW_TIME
        );
    
         
        if($is_default){
            $Member_receive->where(array('uid'=>UID))->setfield('is_default',0);
        }
    
        if($id){
            $data = array(
                'realname' => $realname,
                'mobile' => $mobile,
                'province_id' => $province_id,
                'city_id' => $city_id,
                'area_id' => $area_id,
                'address' => $address,
                'is_default' => $is_default,
                'update_time' => NOW_TIME
            );
            $Member_receive->where(array('id'=>$id))->save($data) !==false  ?
            $this->success('保存成功',U('User/receives')) : $this->error('保存失败');
        }
        else{
            $Member_receive->add($data) ? $this->success("保存成功",U('user/receives')) : $this->error("保存失败");
        }
    }
    
	/* 收藏的商品 */
	public function collectProduct(){
	    
	    !is_login() && $this->referer('User/login', U('User/receives'));
	    
	    $page = I('post.page', 1);
	    $page_size = I('post.page_size', 12);
	    $offset = ($page - 1) * $page_size;
	    
	    $M_product_image = M('product_image');
	    $M_collect = M('collect_product');
	    $map = array();
	    $map['uid'] = UID;
	    
	    $list = $M_collect->limit($offset, $page_size)
	    ->where($map) ->select();
	    
	    foreach($list as &$item){
	        $item['product_title'] = get_table_field($item['product_id'], 'id', 'title', 'product');
	        $item['product_price'] = get_table_field($item['product_id'], 'id', 'price', 'product');
	        $item['image_path']= get_cover(get_table_field($item['product_id'],'product_id','cover_id',
	                'product_image'),'path');
	    }
	    $total=$M_collect->where($map)->count();	  
	    $_page = new \Think\Page($total, $page_size);
	    $this->assign('_list',$list);
	    $this->assign('_page', $_page->show());
	    $this->display();
	}
	
	/* 收藏的店铺 */
	public function collectShop(){
	    !is_login() && $this->referer('User/login', U('User/receives'));
	    $page = I('post.page', 1);
	    $page_size = I('post.page_size', 12);
	    $offset = ($page - 1) * $page_size;
	    
	    $M_collect = M('collect_shop');
	    $map = array();
	    $map['uid'] = UID;
	    
	    $list = $M_collect->limit($offset, $page_size)
	    ->where($map)
	    ->select();  
	    
	    foreach ($list as &$item) {
	        $item['shop_title'] = get_table_field($item['shop_id'], 'id', 'title', 'shop');
	        $item['headpic_path'] = get_cover(get_table_field($item['shop_id'], 'id', 'headpic', 'shop'),'path');
	    }
	    
	    $total=$M_collect->where($map)
	    ->count();
	    $_page = new \Think\Page($total, $page_size);
	    $this->assign('_list',$list);
	    $this->assign('_page', $_page->show());
	    $this->display();
	}
	
	/* 我的足迹 */
	public function marks(){
	    !is_login() && $this->referer('User/login', U('User/receives'));
	    $page = I('post.page', 1);
	    $page_size = I('post.page_size', 12);
	    $offset = ($page - 1) * $page_size;
	     
	    
	    $M_collect = M('collect_browse');
	    $map = array();
	    $map['uid'] = UID;
	    
	    $list = $M_collect->limit($offset, $page_size)
	    ->where($map)
	    ->select();
	    foreach ($list as &$item) {
	        $item['product_title'] = get_table_field($item['product_id'], 'id', 'title', 'product');
	        $item['product_price'] = get_table_field($item['product_id'], 'id', 'price', 'product');
	        $item['image_path']= get_cover(get_table_field($item['product_id'],'product_id','cover_id',
	                'product_image'),'path');
	    }
	    
	    $total=$M_collect->where($map)->count();
	    $_page = new \Think\Page($total, $page_size);
	    $this->assign('_list',$list);
	    $this->assign('_page', $_page->show());
	    $this->display();
	}
	
	/* 所有订单 */
	public function orders(){
	    !is_login() && $this->referer('User/login', U('User/orders'));
	    $type = I('request.type');
	    $M_order=M('order');   
        $keyword=I('order_keyword');
	    $map=array();
	    $map['uid']=UID;
	    
	    //订单统计	
	    $statistics=array();
	    $statistics['pending']=$M_order->where(array('uid'=>UID,'status'=>0))->count()|0;
	    $statistics['shipped']=$M_order->where(array('uid'=>UID,'status'=>1))->count()|0;
	    $statistics['receipt']=$M_order->where(array('uid'=>UID,'status'=>array('BETWEEN','2,4')))->count()|0;
	    $statistics['evaluate']=$M_order->where(array('uid'=>UID,'status'=>5))->count()|0;
	    $statistics['service']=$M_order->where(array('uid'=>UID,'status'=>6))->count()|0;
	    $this->assign('statistics',$statistics);
	    switch($type){
	        case 'pending':
	            $map['status']=0;
	            break;
	        case  'shipped':
	            $map['status']=1;
	            break;
	        case  'receipt':
	            $map['status']=array('between',array(2,4));
	            break;
	        case 'evaluate':
	            $map['status']=5;
	            break;
	        case 'service':
	            $map['status']=6;
	            break;
	    }
	    if($keyword){
	        if(is_numeric($keyword)){
	            $map['order_no']=array('like','%'.$keyword.'%');
	        }
	    }
	    $prefix = C('DB_PREFIX');
	    $l_table = $prefix.('product');
	    $m_table = $prefix.('order');
	    $r_table = $prefix.('order_product');
	    $model=D('product');
	    $model = $model->table($l_table.' l')
	    ->join($r_table . ' r on r.product_id=l.id')
	    ->join($m_table.' m ON m.id=r.order_id');
	     
	    $options['field'] = array('r.product_title','l.security_7days','l.price unit_price',
	            ' l.security_delivery',
	            'l.shop_id','m.price order_price','r.product_id', 'r.price','r.quantity','r.identify_price','r.product_attr','r.is_comment','r.return_status');
	     
	    $OPT = new \ReflectionProperty($model,'options');
	    $OPT->setAccessible(true);
	    $join_map=array();
	    
	    $page=I('p',1);
	    $page <=0 && $page=1;
	    $page_size=8;
	    $offset=($page-1)*$page_size;
	    $total=$M_order->where($map)->count();
	    $list=$M_order->limit($offset,$page_size)->where($map)
	    ->field('id order_id, order_no,status,status short_status,create_time,price total_price,uid')->order('id DESC')->select();
	   
	    int_to_string($list, array('status'=>getStatus('buyer_order'),'short_status'=>getStatus('short_order')));
	     
	    foreach ($list as &$item){
	        $join_map['r.order_id'] = $item['order_id'];
	        $options['where']=$join_map;
	         
	        $options = array_merge( (array)$OPT->getValue($model), $options );
	        $model->setProperty('options',$options);
	        $identify_price=0;
	       
	        $Product_list = $model->select();
	        foreach ($Product_list as &$pro_item){
	            $identify_price+=(double)$pro_item['identify_price'];
	            $pro_item['image_path']=get_cover(get_table_field($pro_item['product_id'],'product_id','cover_id','product_image'),'path');
	        }
	        $item['identify_price']=$identify_price;
	        $item['products']=$Product_list;
	    }
	     
	    int_to_string($list, array('status'=>getStatus('short_order')));
	    $this->assign('order_list',$list);
	    $__PAGE__ = new \Think\Page($total, $page_size);
	    $__PAGE__->lastSuffix = false;
	    $__PAGE__->rollPage = 6;
	    $__PAGE__->setConfig('prev', '<');
	    $__PAGE__->setConfig('next', '>');
	    $__PAGE__->setConfig('first', '<<');
	    $__PAGE__->setConfig('last', '<span>...</span>');
	    $__PAGE__->setConfig('header', '<span>共%TOTAL_PAGE%页</span>');
	    $__PAGE__->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %END% %DOWN_PAGE% %HEADER%');
	    
	    $this->assign('_page', $__PAGE__->show());
	    $this->assign('type', $type);
	    $this->display();
	}
	
	/* 订单详情 */
	public function order(){
	    !is_login() && $this->referer('User/login', U('User/orders'));
	  
	    $order_id=I('request.id');
	     
	    $M_order_product=M('order_product');
	    $M_order=M("order");
	    $M_payment_log=M('payment_log');
	    $M_order_shipping=M('order_shipping');
	     
	    $prefix = C('DB_PREFIX');
	    $l_table = $prefix.('product');
	    $m_table = $prefix.('shop');
	    $r_table = $prefix.('order_product');
	    
	    $model=D('product');
	    $model = $model->table($l_table.' l')
	    ->join($r_table . ' r on r.product_id=l.id');
	    
	    $options['field'] = array('r.product_title','l.security_7days','l.price unit_price',
	            ' l.security_delivery',
	            'l.shop_id','r.product_id', 'r.price unit_price','r.quantity',
	            'r.identify_price','r.product_attr','r.is_comment','r.return_status');
	    $OPT = new \ReflectionProperty($model,'options');
	    $OPT->setAccessible(true);
	    $join_map=array();
	     
	    $order_info=$M_order->field('id order_id, order_no,status,create_time,price total_price,province_id,city_id,consignee,address,mobile')->find($order_id);
	     
	    $short_order=getStatus('short_order');
	    $buyer_order=getStatus('buyer_order');
	    $order_info['short_order']=$short_order[$order_info['status']];
	    $order_info['buyer_order']=$buyer_order[$order_info['status']];
	    if((int)$order_info['status']>=1){
	        $tem_payment=$M_payment_log->where(array('order_id'=>$order_id))->find();
	        $order_info['pay_time']=$tem_payment['create_time'];
	        
	        $order_info['transaction_no']=$tem_payment['transaction_no'];
	    }
	     
	    if((int)$order_info['status']>=2){
	        $tem_order_shipping=$M_order_shipping->where(array('order_id'=>$order_id,'type'=>'seller'))->find();
	        $shipping_info=array();
	        $shipping_info['shipping_code']=$tem_order_shipping['code'];
	        $shipping_info['shipping_time']=$tem_order_shipping['create_time'];
	        $shipping_info['shipping_company']=get_table_field($tem_order_shipping['shipping_code'],'code','title','shipping');
	        $this->assign('shipping_info',$shipping_info);
	    }
	    
	    $order_info['address_full']=
	    get_table_field($order_info['province_id'],'province_id','province','hat_province')
	    .get_table_field($order_info['city_id'],'city_id','city','hat_city')
	    .get_table_field($order_info['area_id'],'area_id','area','hat_area').$order_info['address'];
	    
	    $join_map['r.order_id'] = $order_id;
	    $options['where']=$join_map;
	    
	    $options = array_merge( (array)$OPT->getValue($model), $options );
	    $model->setProperty('options',$options);
	    
	    $Product_list = $model->select();
	    $identify_price=0;
	    foreach ($Product_list as &$pro_item){
	        $identify_price+=(double)$pro_item['identify_price'];
	        $pro_item['image']=get_cover(get_table_field($pro_item['product_id'],'product_id','cover_id','product_image'),'path');
	    }
	    $order_info['identify_price']=$identify_price;
	    $order_info['products']=$Product_list;
	    
	    $type='';
	    switch((int)$order_info['status']){
	        case 0:
	            $type='pending';
	            break;
	        case  1:
	            $type='shipped';	           
	            break;
	        case  2:
	            $type='shipped';	            
	            break;
	        case  3:
	            $type='shipped';	            
	            break;
	        case  4:
	            $type='shipped';            
	            break;
	        case 5:
	            $type='evaluate';
	            break;
	        case 6:
	            $type='service';
	            break;
	    }
	    $this->assign('type', $type);
	    $this->assign('info',$order_info);
	    
	    $M_order_shipping = M('order_shipping');
	    $seller_shipping = $M_order_shipping->where(array('order_id'=>$order_id, 'type'=>'seller'))->find();
	    $admin_shipping = $M_order_shipping->where(array('order_id'=>$order_id, 'type'=>'admin'))->find();
	    $seller_shipping['shipping'] = getExpress($seller_shipping['shipping_code'], $seller_shipping['code']);
	    $admin_shipping['shipping'] = getExpress($admin_shipping['shipping_code'], $admin_shipping['code']);
	    $this->assign('seller_shipping', $seller_shipping);
	    $this->assign('admin_shipping', $admin_shipping);
	    
	    $this->display();
	}
	
	/* 物流明细 */
	public function orderShip(){
        $order_id=I('request.orderid');
        
        $M_order_product=M('order_product');
        $M_order=M('order');
        $M_order_shipping=M('order_shipping');
	    $order_info=$M_order->field('id order_id, order_no,status,create_time,price total_price,province_id,city_id,consignee,address,mobile')->find($order_id);
	   
	    
	    $order_shipping=$M_order_shipping->where(array('order_id'=>$order_id,'type'=>'seller'))->find();
	    
	    if($order_shipping){
    	    $order_info['shipping_code']=$order_shipping['code'];
    	    $order_info['shipping_time']=$order_shipping['create_time'];
    	    $order_info['shipping_company']=get_table_field($order_shipping['shipping_code'],'code','title','shipping');
	    }
	   
	    $order_info['address_full']=
	    get_table_field($order_info['province_id'],'province_id','province','hat_province')
	    .get_table_field($order_info['city_id'],'city_id','city','hat_city')
	    .get_table_field($order_info['area_id'],'area_id','area','hat_area').$order_info['address'];	 
	  
	    $Product_list =  $M_order_product->where(array('order_id'=>$order_id))->field('product_id')->select();	    
	    foreach ($Product_list as &$pro_item){
	        $pro_item['image']=get_cover(get_table_field($pro_item['product_id'],'product_id',
	                'cover_id','product_image'),'path');
	    }
	  
	    $order_info['products']=$Product_list;
	    $this->assign('info',$order_info);
	    
        $seller_shipping = $M_order_shipping->where(array('order_id'=>$order_id, 'type'=>'seller'))->find();
        $admin_shipping = $M_order_shipping->where(array('order_id'=>$order_id, 'type'=>'admin'))->find();
        $seller_shipping['shipping'] = getExpress($seller_shipping['shipping_code'], $seller_shipping['code']);
        $admin_shipping['shipping'] = getExpress($admin_shipping['shipping_code'], $admin_shipping['code']);
        $this->assign('seller_shipping', $seller_shipping);
        $this->assign('admin_shipping', $admin_shipping);
        
        $this->display();
	}
	
	/* 订单评价 */
	public function orderComment(){
	    !is_login() && $this->referer('User/login', U('User/orders'));
	   
	    $order_id=I('request.orderid');
	    
	    $M_order_product=M('order_product');
	    $M_order=M('order');
	    $M_order_shipping=M('order_shipping');
	    $order_info=$M_order->field('id order_id, order_no,status,create_time,price total_price,province_id,city_id,consignee,address,mobile')->find($order_id);
	    	     
	    $Product_list =  $M_order_product->where(array('order_id'=>$order_id))->field('product_id,price,product_title')->select();
	    foreach ($Product_list as &$pro_item){	        
	        $pro_item['image']=get_cover(get_table_field($pro_item['product_id'],'product_id',
	            'cover_id','product_image'),'path');
	    }
	     
	    $order_info['products']=$Product_list;
	    $this->assign('info',$order_info);
	    
	    $M_order=M('order');
	  
	    $this->assign('info',$order_info);
	    $this->display();
	}
	
	/* 订单退款 */
	public function orderCancel(){
	    !is_login() && $this->referer('User/login', U('User/orderCancel'));
	    $orderid=I('orderid');
	    $this->assign('info',M('order')->find($orderid));
	    $this->display();
	}
	
	/**
	 * 我的闲置
	 */
	public function xianzhi(){
	    !is_login() && $this->referer('User/login', U('User/xianzhi'));
	   $p=I('p',1);
	   $p<=0 && $p=1;
	   $pagesize=8;
	   $offset=($p-1)*$pagesize;
	   
	   $M_product=M('product');
	   $map=array('uid'=>UID,'type'=>'xianzhi','is_show'=>1);
	   $total=$M_product->where($map)->count();
	   
	   $product_list=$M_product->where($map)->limit($offset,$pagesize)->order('id DESC')->select();
	   foreach($product_list as &$item){
	       $item['image_path']=get_cover(get_table_field($item['id'],'product_id',
	           'cover_id','product_image'),'path');
	   }
	   $this->assign('product_list',$product_list);
       
	   $__PAGE__ = new \Think\Page($total, $pagesize);
	   $__PAGE__->lastSuffix = false;
	   $__PAGE__->rollPage = 6;
	   $__PAGE__->setConfig('prev', '<');
	   $__PAGE__->setConfig('next', '>');
	   $__PAGE__->setConfig('first', '<<');
	   $__PAGE__->setConfig('last', '<span>...</span>');
	   $__PAGE__->setConfig('header', '<span>共%TOTAL_PAGE%页</span>');
	   $__PAGE__->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %END% %DOWN_PAGE% %HEADER%');
	    
	   $this->assign('_page', $__PAGE__->show());
	   $this->display();
	}
	
	/* 验证码，用于登录和注册 */
	public function verify(){
		$verify = new \Think\Verify();
		$verify->entry(1);
	}

	/**
	 * 获取用户注册错误信息
	 * @param  integer $code 错误编码
	 * @return string        错误信息
	 */
	private function showRegError($code = 0){
		switch ($code) {
			case -1:  $error = '用户名长度必须在16个字符以内！'; break;
			case -2:  $error = '用户名被禁止注册！'; break;
			case -3:  $error = '用户名被占用！'; break;
			case -4:  $error = '密码长度必须在6-30个字符之间！'; break;
			case -5:  $error = '邮箱格式不正确！'; break;
			case -6:  $error = '邮箱长度必须在1-32个字符之间！'; break;
			case -7:  $error = '邮箱被禁止注册！'; break;
			case -8:  $error = '邮箱被占用！'; break;
			case -9:  $error = '手机格式不正确！'; break;
			case -10: $error = '手机被禁止注册！'; break;
			case -11: $error = '手机号被占用！'; break;
			default:  $error = '未知错误';
		}
		return $error;
	}
	/* 登录页面 */
	public function login($username = '', $password = '', $verify = ''){
	
	    if (IS_POST) { // 登录验证	
	        /* 调用UC登录接口登录 */
	        $user = new UserApi();
	        $uid = $user->login($username, $password);
	        if (0 < $uid) { // UC登录成功
	            /* 登录用户 */
	            $Member = D('Member');
	            if ($Member->login($uid)) { // 登录用户
	                // TODO:跳转到登录前页面
	                $url = I('request.referer') ? I('request.referer') : '';
	                if($url){
	                   $this->ajaxReturn(array('status'=>11,'url'=>$url));
	                }else{
	                    $this->success('欢迎您，亲爱的'.get_username($uid));
	                }
	                $this->error($Member->getError());
	            }
	        } else { // 登录失败
	
	            switch ($uid) {
	                case - 1:
	                    $error = '用户不存在或被禁用！';
	                    break; // 系统级别禁用
	                case - 2:
	                    $error = '密码错误！';
	                    break;
	                default:
	                    $error = '未知错误！';
	                    break; // 0-接口参数错误（调试阶段使用）
	            }
	            $this->error($error);
	        }
	    } else {	        
	        // 显示登录表单
	        $referer = session('RETURN_REDIRECT');
	        session('RETURN_REDIRECT', null);
	        empty($referer) && $referer=U('Index/index');
	        is_login() && $this->redirect('User/index');
	        $this->assign('referer', $referer);
	        $this->display();
	    }
	}
	

	/* 密码修改 */
	public function password(){
	    !is_login() && $this->referer('User/login', U('User/password'));
	    if ( IS_POST ) {
	        //获取参数
	        $uid        =   is_login();
	        $password   =   I('post.oldpassword');
	        $repassword = I('post.repassword');
	        $data['password'] = I('post.newpassword');
	        empty($password) && $this->error('请输入原密码');
	        empty($data['password']) && $this->error('请输入新密码');
	        empty($repassword) && $this->error('请输入确认密码');
	         
	        if($data['password'] !== $repassword){
	            $this->error('您输入的新密码与确认密码不一致');
	        }
	         
	        $Api = new UserApi();
	        $res = $Api->updateInfo($uid, $password, $data);
	        if($res['status']){
	            D('Member')->logout();
	            $this->success('修改密码成功请重新登录！',U('login'));
	        }else{
	            $this->error($res['info']);
	        }
	    }else{
	        $this->display();
	    }	
	}
	
	
	/* 忘记密码 */
	public function forgotten(){
	    if(IS_POST){
	        $username=I('username');
	        $verify=I('verify');
	        $password=I('password');
	        $repassword=I('repassword');
	        
	        $user_id=M('ucenter_member')->where(array('username'=>$username))->getfield('id');
	        empty($user_id) && $this->error('账号不存在');
	       
	        empty($password) && $this->error('请输入新密码');
	        empty($repassword) && $this->error('请输入确认密码');
	         
	        if($password !== $repassword){
	            $this->error('您输入的新密码与确认密码不一致');
	        }
	        
	        $M_message_verify=M('message_verify');
	        
	        $verify_map=array('username'=>$username,'code'=>$verify,'type'=>'forgotten','status'=>1,'deadline'=>array('egt',NOW_TIME));
             
	        $verify_result=$M_message_verify->where($verify_map)->order('id DESC')->find();

             if(empty($verify_result)){
                 //$this->error('验证错误');
             }
             $M_message_verify->where(array('username'=>$username))->save(array('status'=>0));
            
             $data['password'] = $password;          
             $Api = new UserApi();
             $res = $Api->updateInfo($user_id,'',$data,1);
            
            if ($res['status']) {
	            D('Member')->logout();
	            $this->success('修改密码成功请重新登录！',U('login'));
	        }else{
	            $this->error($res['info']);
	        }
	    }
	    $this->display();
	}
	
	/* 注册页面 */
	public function register(){
	    if(!C('USER_ALLOW_REGISTER')){
	        $this->error('注册已关闭');
	    }
	    if(IS_POST){ //注册用户	         
	         
	        $username=I('username');
	        $verify=I('verify');
	        $password=I('regpassword');
	        $repassword=I('regrepassword');	 
	        
	        $data['mobile']=$username;
	        $data['password'] = $password;
	        empty($data['password']) && $this->error('请输入新密码');
	        empty($repassword) && $this->error('请输入确认密码');
	         
	        /* 检测密码 */
	        if($password != $repassword){
	            $this->error('密码和重复密码不一致！');
	        }
	
	        $M_message_verify=M('message_verify');
	
	        $verify_map=array('username'=>$username,'code'=>$verify,'type'=>'register','status'=>1,'deadline'=>array('egt',NOW_TIME));
	        //, 'deadline'>=NOW_TIME
	        $verify_result=$M_message_verify->where($verify_map)->order('id DESC')->find();
	       
	        if(empty($verify_result)){
	          
	            $this->error('验证错误');
	        }
	        $M_message_verify->where(array('username'=>$username))->save(array('status'=>0));
	        $data['pasword']=$password;
	         
	        /* 调用注册接口注册用户 */
	        $User = new UserApi;
	        $uid = $User->register($username, $password);
	        if(0 < $uid){ //注册成功
	            //TODO: 发送验证邮件
	            //13565478965
	            $user = array(
	                'uid' => $uid,
	                'nickname' => $username,
	                'status' => 1,
	                'reg_time' => NOW_TIME,
	                'reg_ip' => get_client_ip()
	            );
	            
	            if (! M('Member')->add($user)) {
	                $this->error('注册失败，未知错误！');
	            }
	            
	            $this->success('注册成功！',U('login'));
	        } else { //注册失败，显示错误信息
	            $this->error($this->showRegError($uid));
	        }
	
	    } else { //显示注册表单
	        $this->display();
	    }
	}
	/* 退出登录 */
	public function logout(){
	    if(is_login()){
	        D('Member')->logout();
	        //$this->success('退出成功！', U('User/login'));
	        $this->ajaxReturn(array('status'=>11));
	    } else {
	        //$this->redirect('User/login');
	    }
	}

}
